<!-- 补库退货新增 -->
<template>
    <div class="dialog-box">
        <el-dialog v-model="open" :title="dialogTitle" width="900" close-on-press-escape="false">
            <el-form :model="form" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="关联补库单" required>
                            <el-input v-model="form.outboundOrderNo" placeholder="请选择" suffix-icon="MoreFilled"
                                @click="openSelectOutboundOrder" readonly />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户" required>
                            <el-input disabled v-model="form.customer" placeholder="根据关联出库单带出" readonly />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="退货负责人" required>
                            <el-input v-model="form.manager" placeholder="请选择" suffix-icon="MoreFilled"
                                @focus="openOutboundOrderManagerPopup" readonly />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="负责人电话" required>
                            <el-input disabled v-model="form.managerPhone" placeholder="根据所选负责人带出" readonly />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="退货日期" required>
                            <el-date-picker type="date" placeholder="请选择" v-model="form.returnDate" format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD" style="width: 100%;" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="备注">
                            <el-input v-model="form.note" placeholder="请输入备注" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <div class="supply-products" v-if="form.outboundOrderNo && selectedProducts.length > 0">
                    <div class="title">
                        <div class="title-text">
                            <div class="line"></div>
                            退货产品
                        </div>
                    </div>
                    <el-table border :data="selectedProducts" style="width: 100%">
                        <el-table-column prop="name" label="产品名称" width="auto" />
                        <el-table-column prop="spec" label="规格型号" width="auto" />
                        <el-table-column prop="unit" label="拆零单位" width="auto" />
                        <el-table-column prop="outboundCount" label="出库数量" width="auto" />
                        <el-table-column prop="outboundPrice" label="出库单价" width="auto" />
                        <el-table-column prop="discount" label="折扣" width="auto" />
                        <el-table-column prop="outboundReturn" label="可退货数量" width="auto" />
                        <el-table-column prop="returnCount" label="退货数量" width="120">
                            <template #default="scope">
                                <el-input-number v-model="scope.row.returnCount" :min="0"
                                    :max="scope.row.outboundReturn" :precision="0" size="small"
                                    controls-position="right" @change="handleReturnCountChange(scope.row)"
                                    style="width: 100%;" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="returnAmount" label="退货金额" width="auto">
                            <template #default="scope">
                                ¥{{ calculateReturnAmount(scope.row) }}
                            </template>
                        </el-table-column>
                    </el-table>


                </div>

                <!-- 当未选择出库单时显示提示 -->
                <div class="no-products-tip" v-if="!form.outboundOrderNo">
                    <el-empty description="请先选择关联补库单，然后系统将自动加载可退货产品列表" :image-size="120" />
                </div>

                <!-- 当选择了出库单但没有可退货产品时显示提示 -->
                <div class="no-products-tip" v-else-if="form.outboundOrderNo && selectedProducts.length === 0">
                    <el-empty description="该出库单暂无可退货产品" :image-size="120" />
                </div>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="open = false">取消</el-button>
                    <el-button color="#626aef" @click="handleSubmit">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>

    <!-- 关联补库单弹窗 -->
    <AssociatedOutboundForm ref="associatedOutboundFormRef" @selectOutboundOrder="handleSelectOutboundOrder" />
    <!-- 退货负责人弹窗 -->
    <ReturnManager ref="returnManagerRef" @selectManager="handleSelectManager" />
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
import { ElMessage } from 'element-plus';
import AssociatedOutboundForm from "./AssociatedOutboundForm.vue";
import ReturnManager from "./ReturnManager.vue";
import api from "@/api";
// 定义事件发射器
const emit = defineEmits(['refresh']);

const open = ref<boolean>(false); // 弹窗控制器
const form = reactive<any>({
    id: "",//退货单id
    outboundOrderNo: "",  // 关联出库单号
    customer: "",         // 客户名称
    manager: "",          // 负责人
    managerPhone: "",     // 负责人电话
    returnDate: "",       // 退货日期
    remark: "",           // 备注
    orderDiscount: "0",   // 整单折扣
    totalReturnAmount: "0.00", // 退货成交额
    // 内部使用的额外字段
    selectedOutboundOrder: null, // 选中的出库单完整信息
    selectedManager: null,       // 选中的负责人完整信息
});

// 动态弹窗标题
const dialogTitle = computed(() => {
    return form.id && form.id !== "" ? "编辑退货单" : "新增退货单";
});

// 关联出库单弹窗引用
const associatedOutboundFormRef = ref<any>(null);
// 退货负责人弹窗引用
const returnManagerRef = ref<any>(null);

// 存储选中的产品列表
const selectedProducts = ref<any[]>([]);

// 获取退货产品列表，回显的时候调用这个来回显退货产品
const getReturnProductData = async () => {
    if (!form.id) {
        console.warn('退货单ID不存在，无法获取退货产品数据');
        return;
    }

    try {
        const res = await api.Outbound.getoutboundReturnProductListByOrderId({
            id: form.id
        });

        if (res.code === 200) {
            console.log('获取退货产品回显数据:', res.data);

            // 处理回显数据，转换为组件需要的格式
            selectedProducts.value = res.data.product_data.map((item: any) => ({
                id: Number(item.product_id || item.id),
                name: item.product_name || item.name || item.spu_name,
                spec: item.specification || item.spec,
                unit: item.open_unit_name || item.measure_unit_name,
                outboundCount: Number(item.out_num || 0),
                outboundReturn: Number(item.return_num || item.can_return_num || 0), // 已退货数量作为可退货数量显示
                outboundPrice: parseFloat(item.price || item.out_price || 0),
                discount: parseFloat(item.discount || 100),
                returnCount: Number(item.return_num || 0), // 已退货数量
                returnPrice: parseFloat(item.price || item.out_price || 0),
                returnAmount: parseFloat(item.return_num || 0) * parseFloat(item.price || 0) // 计算退货金额
            }));

            // 重新计算总金额
            calculateTotalAmount();

            console.log('退货产品回显完成，产品数量:', selectedProducts.value.length);
            ElMessage.success(`已加载 ${selectedProducts.value.length} 个退货产品`);
        } else {
            ElMessage.error(res.message || '获取退货产品数据失败');
            selectedProducts.value = [];
        }
    } catch (error) {
        console.error('获取退货产品数据失败:', error);
        ElMessage.error('获取退货产品数据失败');
        selectedProducts.value = [];
    }
};


// 获取可退货产品列表
const getReturnProductList = async (outboundOrderId: string | number) => {
    if (!outboundOrderId) {
        console.warn('未提供出库单ID，无法获取退货产品列表');
        return;
    }

    try {
        const res = await api.Outbound.getoutboundReturnProductList({
            id: outboundOrderId // 传递选择的关联补库单id
        });

        if (res.code === 200) {
            // 获取可退货产品列表
            const returnProductList = res.data;
            console.log('可退货产品列表:', returnProductList);

            // 处理产品数据，转换为组件需要的格式
            selectedProducts.value = returnProductList.map((item: any) => ({
                id: Number(item.id || item.product_id), // 确保ID是数字类型
                name: item.name || item.product_name || item.spu_name,
                spec: item.specification || item.spec,
                unit: item.open_unit_name,
                outboundCount: item.out_num,
                outboundReturn: item.can_return_num,
                outboundPrice: parseFloat(item.out_price || item.price || 0),
                discount: parseFloat(item.discount || 0),
                returnCount: 0, // 初始退货数量为0
                returnPrice: parseFloat(item.out_price || item.price || 0), // 退货单价默认等于出库单价
                returnAmount: 0 // 初始退货金额为0
            }));

            // 重新计算总金额
            calculateTotalAmount();

            ElMessage.success(`已加载 ${selectedProducts.value.length} 个可退货产品`);
        } else {
            ElMessage.error(res.message || '获取可退货产品列表失败');
            selectedProducts.value = [];
        }
    } catch (error) {
        console.error('获取可退货产品列表失败:', error);
        ElMessage.error('获取可退货产品列表失败');
        selectedProducts.value = [];
    }
};

// 打开弹窗 - 支持编辑模式
const openLoading = async (editData?: any) => {
    open.value = true;

    if (editData) {
        // 编辑模式：填充现有数据
        console.log('编辑模式，填充数据:', editData);
        form.id = editData.id || ""; // 退货单ID
        form.outboundOrderNo = editData.outbound_order_no || "";
        form.customer = editData.customer_name || "";
        form.manager = editData.manager_name || "";
        form.managerPhone = editData.manager_phone || "";
        form.returnDate = editData.return_date || "";
        form.note = editData.note || editData.remark || ""; // 兼容不同字段名
        form.orderDiscount = editData.order_discount || "0";
        form.totalReturnAmount = editData.total_return_amount || "0.00";

        // 保存完整的出库单信息（用于支持重新选择）
        form.selectedOutboundOrder = {
            id: editData.outbound_order_id,
            orderNo: editData.outbound_order_no,
            customer: editData.customer_name
        };

        // 保存完整的负责人信息（用于支持重新选择）
        form.selectedManager = {
            id: editData.manager_member_id || editData.manager_id,
            name: editData.manager_name,
            phone: editData.manager_phone
        };

        // 编辑模式：使用 getReturnProductData 回显已保存的退货产品数据
        if (form.id) {
            await getReturnProductData();
        }

        console.log('编辑模式数据加载完成');
    } else {
        // 新增模式：初始化表单数据
        initializeForm();
    }
};

// 初始化表单
const initializeForm = () => {
    form.id = ""; // 清空退货单ID
    form.outboundOrderNo = "";
    form.customer = "";
    form.manager = "";
    form.managerPhone = "";
    form.returnDate = "";
    form.note = ""; // 修正字段名从remark到note
    form.orderDiscount = "0";
    form.totalReturnAmount = "0.00";
    form.selectedOutboundOrder = null;
    form.selectedManager = null;
    selectedProducts.value = [];

    console.log('表单已初始化');
};

// 打开关联出库单弹窗
const openSelectOutboundOrder = () => {
    if (!associatedOutboundFormRef.value) {
        ElMessage.error('关联出库单组件未就绪');
        return;
    }

    // 传递当前选中的出库单信息（如果有的话）
    const currentOutboundOrder = form.selectedOutboundOrder;
    associatedOutboundFormRef.value.openDialog(currentOutboundOrder);
};

// 处理选择出库单
const handleSelectOutboundOrder = async (outboundOrder: any) => {
    console.log('选择的出库单数据:', outboundOrder);

    if (!outboundOrder) {
        ElMessage.warning('未选择有效的出库单');
        return;
    }

    // 保存完整的出库单信息
    form.selectedOutboundOrder = outboundOrder;

    // 填充表单显示字段
    form.outboundOrderNo = outboundOrder.orderNo || outboundOrder.order_no || "";
    form.customer = outboundOrder.customer || outboundOrder.customer_name || "";

    // 清除之前选择的负责人信息（因为更换了出库单）
    form.manager = "";
    form.managerPhone = "";
    form.selectedManager = null;

    // 验证必要字段
    if (!form.outboundOrderNo) {
        ElMessage.warning('出库单号信息缺失');
        return;
    }

    if (!form.customer) {
        ElMessage.warning('客户信息缺失');
        return;
    }

    // 获取出库单ID用于调用退货产品列表API
    const outboundOrderId = outboundOrder.id;
    if (!outboundOrderId) {
        ElMessage.warning('出库单ID缺失，无法获取退货产品列表');
        return;
    }

    // 当用户切换关联补库单时，调用 getReturnProductList 获取新的可退货产品列表
    // 这会覆盖之前的产品数据（无论是编辑回显的还是之前选择的）
    await getReturnProductList(outboundOrderId);

    ElMessage.success(`已关联出库单：${form.outboundOrderNo}`);
};

// 选择退货负责人
const openOutboundOrderManagerPopup = (e: any) => {
    if (!returnManagerRef.value) {
        ElMessage.error('退货负责人组件未就绪');
        return;
    }

    // 传递当前选中的负责人信息（如果有的话）
    const currentManager = form.selectedManager;
    returnManagerRef.value.openLoading(currentManager);

    // 移除输入框焦点
    if (e && e.target) {
        e.target.blur();
    }
};

// 处理选择退货负责人
const handleSelectManager = (manager: any) => {
    console.log('选择的负责人数据:', manager);

    if (!manager) {
        ElMessage.warning('未选择有效的负责人');
        return;
    }

    // 保存完整的负责人信息
    form.selectedManager = manager;

    // 填充表单显示字段
    form.manager = manager.name || "";
    form.managerPhone = manager.phone || manager.mobile || "";

    // 验证必要字段
    if (!form.manager) {
        ElMessage.warning('负责人姓名信息缺失');
        return;
    }

    if (!form.managerPhone) {
        ElMessage.warning('负责人电话信息缺失');
        return;
    }

    ElMessage.success(`已选择负责人：${form.manager}`);
};

// 计算退货总产品数量
const totalReturnCount = computed(() => {
    return selectedProducts.value.reduce((total, product) => {
        return total + (product.returnCount || 0);
    }, 0);
});

// 处理退货数量变化
const handleReturnCountChange = (row: any) => {
    // 确保退货数量不超过可退货数量
    if (row.returnCount > row.outboundReturn) {
        row.returnCount = row.outboundReturn;
        ElMessage.warning(`退货数量不能超过可退货数量 ${row.outboundReturn}`);
    }

    // 确保退货数量不小于0
    if (row.returnCount < 0) {
        row.returnCount = 0;
    }

    // 重新计算该产品的退货金额
    calculateReturnAmount(row);

    // 重新计算总金额
    calculateTotalAmount();

    console.log(`产品 ${row.name} 退货数量变更为: ${row.returnCount}`);
};

// 计算退货金额
const calculateReturnAmount = (row: any) => {
    const count = parseFloat(row.returnCount || 0);
    const price = parseFloat(row.outboundPrice || 0);
    const discount = parseFloat(row.discount || 100) / 100; // 折扣转换为小数

    const amount = count * price * discount;
    row.returnAmount = amount.toFixed(2);
    return row.returnAmount;
};

// 计算总退货金额
const calculateTotalAmount = () => {
    let total = 0;

    selectedProducts.value.forEach(product => {
        const productAmount = parseFloat(calculateReturnAmount(product));
        total += productAmount;
    });

    // 应用整单折扣
    const orderDiscountRate = parseFloat(form.orderDiscount || 100) / 100;
    total = total * orderDiscountRate;

    form.totalReturnAmount = total.toFixed(2);
    console.log('计算总退货金额:', form.totalReturnAmount);
};

// 监听产品数据变化，重新计算总金额
watch(selectedProducts, () => {
    calculateTotalAmount();
}, { deep: true });

// 监听整单折扣变化，重新计算总金额
watch(() => form.orderDiscount, () => {
    calculateTotalAmount();
});

// 表单验证
const validateForm = () => {
    const errors: string[] = [];

    if (!form.outboundOrderNo) {
        errors.push('请选择关联补库单');
    }

    if (!form.customer) {
        errors.push('客户信息缺失');
    }

    if (!form.manager) {
        errors.push('请选择退货负责人');
    }

    if (!form.managerPhone) {
        errors.push('负责人电话信息缺失');
    }

    if (!form.returnDate) {
        errors.push('请选择退货日期');
    }

    if (selectedProducts.value.length === 0) {
        errors.push('请先选择关联补库单以加载可退货产品');
    }

    // 检查是否至少有一个产品设置了退货数量
    const hasReturnProducts = selectedProducts.value.some(product =>
        product.returnCount && product.returnCount > 0
    );

    if (!hasReturnProducts) {
        errors.push('请至少为一个产品设置退货数量');
    }

    // 验证每个有退货数量的产品数据
    for (const product of selectedProducts.value) {
        if (product.returnCount && product.returnCount > 0) {
            if (product.returnCount > product.outboundReturn) {
                errors.push(`产品"${product.name}"的退货数量(${product.returnCount})不能超过可退货数量(${product.outboundReturn})`);
                break;
            }

            if (!product.id) {
                errors.push(`产品"${product.name}"的ID信息缺失`);
                break;
            }
        }
    }

    return errors;
};

// 提交表单
const handleSubmit = async () => {
    console.log('开始提交退货单');

    // 表单验证
    const errors = validateForm();
    if (errors.length > 0) {
        ElMessage.error(errors[0]);
        return;
    }

    // 格式化日期为 YYYY-MM-DD 格式
    let formattedDate = '';
    if (form.returnDate) {
        if (form.returnDate instanceof Date) {
            formattedDate = form.returnDate.toISOString().split('T')[0];
        } else if (typeof form.returnDate === 'string') {
            formattedDate = form.returnDate;
        }
    }

    // 筛选出有退货数量的产品
    const returnProducts = selectedProducts.value.filter(product =>
        product.returnCount && product.returnCount > 0
    );

    if (returnProducts.length === 0) {
        ElMessage.error('请至少为一个产品设置退货数量');
        return;
    }

    // 判断是编辑模式还是新增模式
    const isEditMode = form.id && form.id !== "";

    // 准备提交数据，严格按照API文档格式
    const submitData: any = {
        outbound_order_id: Number(form.selectedOutboundOrder?.id), // 补库单ID (integer)
        manager_member_id: Number(form.selectedManager?.id), // 负责人ID (integer) 
        note: form.note || "", // 备注 (string)
        return_date: formattedDate, // 退货日期 (string) 格式: YYYY-MM-DD
        product_data: returnProducts.map(product => ({
            id: Number(product.id), // 产品ID (integer)
            num: Number(product.returnCount) // 退货数量 (number) 拆零单位
        }))
    };

    // 如果是编辑模式，添加退货单ID
    if (isEditMode) {
        submitData.id = Number(form.id); // 退货单ID
    }

    console.log('准备提交的数据:', submitData);
    console.log('提交模式:', isEditMode ? '编辑模式' : '新增模式');
    console.log('退货产品明细:', returnProducts.map(p => ({
        name: p.name,
        id: p.id,
        returnCount: p.returnCount,
        maxReturn: p.outboundReturn
    })));

    // 最终数据验证
    if (!submitData.outbound_order_id || isNaN(submitData.outbound_order_id)) {
        ElMessage.error('补库单ID无效，请重新选择补库单');
        return;
    }

    if (!submitData.manager_member_id || isNaN(submitData.manager_member_id)) {
        ElMessage.error('负责人ID无效，请重新选择负责人');
        return;
    }

    if (!submitData.return_date || !/^\d{4}-\d{2}-\d{2}$/.test(submitData.return_date)) {
        ElMessage.error('退货日期格式无效，请重新选择日期');
        return;
    }

    // 编辑模式下验证退货单ID
    if (isEditMode && (!submitData.id || isNaN(submitData.id))) {
        ElMessage.error('退货单ID无效，无法进行编辑操作');
        return;
    }

    // 验证产品数据
    for (const product of submitData.product_data) {
        if (!product.id || isNaN(product.id)) {
            ElMessage.error('存在无效的产品ID，请重新加载产品列表');
            return;
        }
        if (!product.num || isNaN(product.num) || product.num <= 0) {
            ElMessage.error('存在无效的退货数量，请检查输入');
            return;
        }
    }

    try {
        console.log(`正在调用${isEditMode ? '编辑' : '新增'}退货单API...`);

        let res;
        if (isEditMode) {
            // 编辑模式：调用编辑API
            res = await api.Outbound.editoutboundReturn(submitData);
        } else {
            // 新增模式：调用新增API
            res = await api.Outbound.addoutboundReturn(submitData);
        }

        console.log('API返回结果:', res);

        if (res.code === 200) {
            const actionText = isEditMode ? '编辑' : '创建';
            ElMessage.success(`退货单${actionText}成功！共退货 ${returnProducts.length} 种产品，总数量 ${totalReturnCount.value}`);
            emit('refresh');
            open.value = false;

            // 重置表单
            initializeForm();
        } else {
            const actionText = isEditMode ? '编辑' : '创建';
            ElMessage.error(res.message || `${actionText}退货单失败`);
        }
    } catch (error) {
        const actionText = isEditMode ? '编辑' : '创建';
        console.error(`${actionText}退货单失败:`, error);
        ElMessage.error(`网络错误，${actionText}失败`);
    }
};

defineExpose({
    openLoading,
});
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
    --el-dialog-padding-primary: 0px;
}

::v-deep .el-dialog__header {
    padding: 10px 16px;
    border-bottom: 1px solid #f0f0f0;
    font-weight: bold;
}

::v-deep .dialog-footer {
    padding: 10px 16px;
    border-top: 1px solid #f0f0f0;
}

::v-deep .el-dialog__headerbtn .el-dialog__close {
    color: #000;
}

::v-deep .el-dialog__body {
    padding: 10px 10px;
}

:deep(.el-form-item__label) {
    justify-content: flex-start;
}

:deep(.el-form-item) {
    flex-direction: column;
    margin-bottom: 7px;
}

:deep(.el-select__wrapper) {
    background: #fafcfb;
}

:deep(.el-badge__content.is-fixed) {
    color: #666;
    border-radius: 3px;
    padding: 4px;
}

:deep(.el-table .cell) {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 4px 8px;
}

:deep(.el-input-number) {
    .el-input__wrapper {
        padding-left: 8px;
        padding-right: 8px;
    }
}

:deep(.el-input-number__decrease),
:deep(.el-input-number__increase) {
    width: 24px;
    height: 20px;
    line-height: 18px;
    font-size: 12px;
}

:deep(.el-button:hover) {
    color: #6860ff;
    background: #f4f5f7;
}

:deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    width: 100%;
}

:deep(.el-input__wrapper:hover) {
    box-shadow: inset 0 0 0 1px #6860ff;
}

.supply-products {
    margin-top: 20px;

    .title {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 10px;
        font-weight: bold;

        .title-text {
            display: flex;
            align-items: center;

            .line {
                height: 17px;
                width: 2px;
                border-radius: 12px;
                margin-right: 8px;
                background-color: #6860ff;
            }
        }
    }

    .summary-info {
        margin-top: 16px;
        padding: 16px;
        background-color: #f8f9fa;
        border-radius: 6px;
        border: 1px solid #e9ecef;

        :deep(.el-form-item) {
            margin-bottom: 0;
        }

        :deep(.el-form-item__label) {
            font-weight: 500;
            color: #495057;
        }

        :deep(.el-input__wrapper) {
            background-color: #fff;
        }

        :deep(.el-input-number) {
            width: 100%;
        }
    }
}

.image-list {
    display: flex;
    gap: 8px;

    .el-image {
        width: 40px;
        height: 40px;
        border-radius: 4px;
    }
}

.no-products-tip {
    margin-top: 20px;
    padding: 40px 20px;
    background-color: #fafafa;
    border-radius: 8px;
    text-align: center;
}

</style>